package com.hp.activiti.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.hp.activiti.filter.JWTAuthenticationFilter;
import com.hp.activiti.filter.JWTLoginFilter;
import com.hp.activiti.security.service.MyUserDetailsService;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private MyUserDetailsService myUserDetailsService;

	@Autowired
	private PasswordEncoder passwordEncoder;

	// 初始化静态
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.headers().frameOptions().disable() // 去掉X-Frame-Options 引起的页面加载错误
				.and().formLogin() // 配置表单登录
				.loginPage("/index.html") // 指定登录页是"/index"
				.loginProcessingUrl("/login").defaultSuccessUrl("/main.html", true) // 登录成功后默认跳转到"/main",true-启动后一直用这个登录成功的配置
				.and().logout().logoutSuccessUrl("/index.html") // 退出登录后的默认url是"/index"
				.and().authorizeRequests().antMatchers("/index.html").permitAll().anyRequest().authenticated() // 其他所有资源都需要认证，登陆后访问
				.and().csrf().disable()
				.addFilter(new JWTLoginFilter(authenticationManager()))
				.addFilter(new JWTAuthenticationFilter(authenticationManager()));
	}

	// 过滤掉静态资源
	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/**/*.css", "/**/*.jpg", "/**/*.js", "/**/*.png", "/**/*.woff2");
	}

}
